package system.parser;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class Sys_ModelParser {
	
	public List parser(Object Entity, List mappings){
		List objL = new ArrayList();		
		if(this.check(Entity)){
			Iterator iter = mappings.iterator();
			while(iter.hasNext()){
				objL.add(this.parse(Entity, (Map)iter.next()));
			}
			return objL;
		}else{
			return null;
		}
	}
	
	private Object parse(Object Entity, Map mapping){		
		try {
			Object obj = Class.forName(Entity.getClass().getName()).newInstance();
			Field[] fields = obj.getClass().getDeclaredFields();
			for(Integer i=1;i<=fields.length;i++){
				String fieldName = fields[i-1].getName();
				String SetterName = "set" + String.valueOf(fieldName.charAt(0)).toUpperCase() + fieldName.substring(1);
				Object val = null;
				try{
					val = mapping.get(fieldName);		
					obj.getClass().getDeclaredMethod(SetterName, fields[i-1].getType()).invoke(obj, val);
				}catch (NoSuchMethodException e) {
					e.printStackTrace();
					continue;
				} 				
			}
			return obj;
		} catch (Exception ex){
			ex.printStackTrace();
			return null;
		}
	}
	
	private boolean check(Object Entity){
		try {
			Class.forName(Entity.getClass().getName()).newInstance();
			return true;
		} catch (ClassNotFoundException e){
			e.printStackTrace();
			return false;
		} catch (Exception ex){
			return false;
		}	
	}
	
}
